package logic

import (
	"context"
	"github.com/google/uuid"
	"muke-network/srv/muke"

	"muke-network/api/internal/svc"
	"muke-network/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateLogic) Create(req *types.CreateRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	userid := 1

	info, err := l.svcCtx.MukeSrv.GoodsInfo(l.ctx, &muke.GoodsInfoRequest{GoodsId: req.GoodsId})
	if err != nil {
		return &types.Response{
			Msg:  err.Error(),
			Code: 500,
			Data: nil,
		}, nil
	}
	if req.Num > info.GoodsStock {
		return &types.Response{
			Msg:  "库存不足",
			Code: 500,
			Data: nil,
		}, nil
	}
	amount := info.GoodsPrice * float32(req.Num)

	orderSn := uuid.NewString()
	order, err := l.svcCtx.MukeSrv.CreateOrder(l.ctx, &muke.CreateOrderRequest{
		UserId:  int64(userid),
		GoodsId: req.GoodsId,
		Amount:  amount,
		OrderSn: orderSn,
	})
	if err != nil {
		return &types.Response{
			Msg:  err.Error(),
			Code: 500,
			Data: nil,
		}, nil
	}

	return &types.Response{
		Msg:  "订单创建成功",
		Code: 200,
		Data: map[string]interface{}{
			"order": order,
		},
	}, nil
}
